/*
 * @Author: xiaosihan 
 * @Date: 2021-04-11 16:20:16 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2021-11-07 16:30:49
 */
import { Clock } from "three";

class Xrt_util {

    constructor() { }

    // 任务队列
    isRuning: boolean = false;

    workList: Array<() => void> = [];

    // 时钟对象
    clock = new Clock();

    // 按照任务队列依次执行 性能优化
    /**
     *
     *
     * @param {() => void} [callback]
     * @param {boolean} [first=true] 需要优先执行
     * @returns
     * @memberof Xrt_util
     */
    requestAnimationFrame(callback?: () => void, first: boolean = false) {

        // 加入任务队列
        if (callback && !this.workList.includes(callback)) {
            if (first) {
                this.workList.splice(1, 0, callback); // 优先执行的任务回调
            } else {
                this.workList.push(callback);
            }
        }

        if (this.isRuning) {
            return;
        }

        // 没有任务需要执行的话就停止执行
        if (this.workList.length === 0) {
            this.isRuning = false;
            return;
        } else {
            this.isRuning = true;
        }

        requestAnimationFrame(() => {
            let callback = this.workList.splice(0, 1)[0];
            callback();
            this.isRuning = false;
            this.requestAnimationFrame();
        });
    }

}

const xrt_util = new Xrt_util();

export default xrt_util;

